package com.gudaichaoren.spider.interceptors;

import cn.hutool.json.JSONUtil;
import com.gudaichaoren.spider.annotations.AllowAnonymous;
import com.gudaichaoren.spider.constant.Constants;
import com.gudaichaoren.spider.entity.User;
import com.gudaichaoren.spider.exception.BusinessException;
import com.gudaichaoren.spider.global.ThreadLocalUtil;
import com.gudaichaoren.spider.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;
                                                                                              
    private static final String HEADER_TOKEN = "Authorization";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if (handlerMethod.getMethod ().getAnnotation (AllowAnonymous.class) != null) {
            return true;
        }
        //通过token去redis获取session
        if (request.getHeader (HEADER_TOKEN)==null) {
            throw new BusinessException (Constants.Response.NO_TOKEN_ERROR);
        }
        String redisSession = redisUtil.get (Constants.RedisConstant.USER_TOKEN_PREFIX+request.getHeader (HEADER_TOKEN));
        if (redisSession==null) {
            throw new BusinessException(Constants.Response.BAD_TOKEN_ERROR);
        }
        User user = JSONUtil.toBean(redisSession, User.class);
        //将session信息存入threadLocal
        ThreadLocalUtil.setSessionThreadLocal (user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除threadLocal
        ThreadLocalUtil.removeSessionThreadLocal ();
    }
}
